package cn.ctwing.ws.client.impl;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import cn.ctwing.ws.client.api.IChannelWatcher;
import cn.ctwing.ws.client.api.IWSChannel;

public class WSChannelWatcher implements IChannelWatcher {
	Map<String,WatchThread> pool = new ConcurrentHashMap<String,WatchThread>();
	@Override
	public void onMissingConnection(IWSChannel channel) {
		WatchThread wt = pool.get(channel.getId());
		if(wt==null) {
			wt = new WatchThread(channel);
			pool.put(channel.getId(), wt);
			wt.start();
		}
		
	}

	@Override
	public void onChannelStartup(IWSChannel channel) {

	}

	@Override
	public void onResume(IWSChannel channel) {
		try {
		pool.remove(channel.getId());
		}catch(Exception e) {}
	}

}

/**
 * 
 * @author eric
 *
 */
class WatchThread extends Thread{
	
	IWSChannel channel;
	
	public WatchThread(IWSChannel channel) {
		this.channel=channel;
	}

	@Override
	public void run() {
		while(!channel.isActive()) {
			System.out.println(channel+"\treconnecting ... ");
			channel.reTry();
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
	
}
